/*
@file: main.cpp
@author: ZZH
@time: 2021-12-27 15:27:26
@info: edl编译器主文件
*/
#include <iostream>
#include <cstdio>
#include "ast.h"
#include "grammar.h"
#include "glbRef.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/ADT/SmallVector.h"
using namespace std;
extern int yydebug;

llvm::Module* theModule;
llvm::LLVMContext theContext;
llvm::IRBuilder<> Builder(theContext);

FILE* f;
list<ASTNode_t*> astList;
int main(int argc, const char** argv)
{
    // yydebug = 1;
    theModule = new llvm::Module("az", theContext);
    f = fopen("std.edl", "r");
    theModule->setSourceFileName("std.edl");
    if (f == NULL)
    {
        // cout << "can`t open file" << endl;
        fclose(f);
        f = fopen("../std.edl", "r");
        if (f == NULL)
        {
            cout << "can`t open file" << endl;
            fclose(f);
            return -1;
        }
    }
    yyrestart(f);
#if 1

    try
    {
        yyparse();
    }
    catch (const std::exception& e)
    {
        cerr << "语法分析过程中捕获到标准异常:" << e.what() << endl;
    }
    catch (...)
    {
        cerr << "语法分析过程中捕获到未知异常" << endl;
    }

#else
    int sym = 0;
    do
    {
        sym = yylex();
        if (sym < 255)
            cout << "sym is:" << (char) sym << endl;
        else
            cout << "sym is:" << (int) sym << endl;
    } while (sym != 0);
#endif
    
    cout << "ast.len:" << astList.size() << endl;

    try
    {
        for (auto ast : astList)
        {
            auto code = ast->codeGen();
            if (nullptr != code)
                code->print(llvm::outs(), true);
            cout << endl;
        }
    }
    catch (const std::exception& e)
    {
        cerr << "语义分析过程中捕获到标准异常:" << e.what() << endl;
    }
    catch (...)
    {
        cerr << "语义分析过程中捕获到未知异常" << endl;
    }

    // error_code ecode;
    // llvm::raw_fd_stream stream ("build/output.bc", ecode);

    // llvm::WriteBitcodeToFile(*theModule, stream);

    theModule->print(llvm::outs(), nullptr);

    for (auto ast : astList)
    {
        delete ast;
    }

    // cout << "VarList.len:" << VariableTable.global()->size() << endl;

    // for (auto var : *VariableTable.global())
    // {
    //     var.second->printInfo();
    // }

    // cout << "function number:" << FunctionTable.size() << endl;
    // for (auto func : FunctionTable)
    // {
    //     func.second->printInfo();
    // }
    return 0;
}
